<?php


namespace App\Imports;

use App\Exceptions\ApiException;
use App\Models\PartCompany;
use App\Models\User;
use App\Services\OrganizeService;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class OrganizeUsersImport implements ToModel, SkipsEmptyRows, WithStartRow
{
    protected $startRow;
    protected $importCountKey;

    public function __construct($importCountKey)
    {
        $this->importCountKey = $importCountKey;
        $this->startRow       = 1;  //从第几行开始
    }

    public function model(array $row)
    {
        $this->checkFormat($row);

        $companyId    = request()->input('company_id'); //一定存在
        $projectId    = request()->input('project_id');
        $departmentId = request()->input('department_id');

        $nickname     = format_str($row[0]); //姓名
        $phone        = format_str($row[1]); //手机号
        $pTitle       = format_str($row[2]); //参建单位
        $pType        = format_str($row[3]); //单位类型
        $contract_num = format_str($row[4]); //责任者

        if ($pTitle && !$projectId) {
            throw new ApiException('请指定项目！');
        }
        if ($nickname && $nickname != '姓名') {
            if (is_phone_number($phone)) { //手机号合法
                $userInfo = User::firstOrCreate(
                    ['phone' => $phone],
                    ['nickname' => $nickname, 'password' => $phone, 'no_hash_pwd' => $phone, 'creator_id'  => user_id(), 'status'=>1]
                );
                $userId = $userInfo->id;
                OrganizeService::addCompanyUser($companyId, $userId);
                OrganizeService::addProjectUser($projectId, $userId);
            } else {
                throw new ApiException($nickname."用户【{$nickname}】导入失败，手机号【{$phone}】不合法");
            }
            redis()->incr($this->importCountKey); //导入的数据量加

            if ($pTitle) { //如果有参建单位
                $partCompany  = PartCompany::firstOrCreate(
                    ['title' => $pTitle, 'type' => self::getTyeByTitle($pType)],
                    ['company_id' => company_id(), 'project_id' => $projectId, 'creator_id' => user_id(), 'contract_num' => $contract_num]
                );
                OrganizeService::addPartCompanyUser($partCompany->id, $userId);
            }
            if ($departmentId) { //如果指定了部门
                OrganizeService::addDepartmentUser($departmentId, $userId);
            }
        }
    }

    /**
     * 检查格式是否正确，判断列的属性
     *
     * @param $row
     * @throws ApiException
     * @author: lxk
     * @date: 2023/9/21 14:02
     */
    public function checkFormat($row)
    {
        if (format_table_label($row[0]) == '姓名') {
            if (format_table_label($row[1]) != '手机号'
                || format_table_label($row[2]) != '参建单位'
                || format_table_label($row[3]) != '单位类型'
                || format_table_label($row[4]) != '责任者'
            ) {
                throw new ApiException("格式错误！列属性名必须和模板完全一致，请下载模板，核对数据列【A~D】");
            }
        }
    }

    /**
     * 获取 参见单位类型id
     *
     * @param $title
     * @return int
     * @throws ApiException
     * @author: lxk
     * @date: 2023/9/21 16:24
     */
    public static function getTyeByTitle($title)
    {
        $arr = [
            '建设' => 1,
            '监理' => 2,
            '施工' => 3,
        ];
        if (!isset($arr[$title])) {
            throw new ApiException('单位类型文字请使用 建设、监理或施工');
        }

        return $arr[$title];
    }

    /**
     * 从第几行开始读取
     *
     * @return int
     * @author: lxk
     * @date: 2023/9/21 14:04
     */
    public function startRow(): int
    {
       return $this->startRow;
    }


}
